<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属店铺" prop="businessId">
        <el-input
          v-model="queryParams.businessId"
          placeholder="请输入所属店铺ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺分类" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入店铺分类名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAddFirstLevel"
          v-hasPermi="['lkshop:businessClass:add']"
        >添加一级分类</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Refresh"
          @click="handleRefresh"
        >刷新列表</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 树形表格 -->
    <el-table
      v-loading="loading"
      :data="businessClassList"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      default-expand-all
    >
      <el-table-column label="分类名称" prop="name" min-width="200">
        <template #default="scope">
          <span :style="{ paddingLeft: (scope.row.level - 1) * 20 + 'px' }">
            {{ scope.row.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="分类等级" align="center" prop="level" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.level === 1" type="primary">一级分类</el-tag>
          <el-tag v-else-if="scope.row.level === 2" type="success">二级分类</el-tag>
          <el-tag v-else type="warning">三级分类</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" align="center" prop="goodsType" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.goodsType === 1" type="info">实物商品</el-tag>
          <el-tag v-else-if="scope.row.goodsType === 2" type="warning">虚拟商品</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="分类图片" align="center" prop="img" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.img" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['lkshop:businessClass:edit']">编辑</el-button>
          <el-button 
            v-if="scope.row.level === 1 || scope.row.level === 2" 
            link 
            type="success" 
            icon="Plus" 
            @click="handleAddSubCategory(scope.row)" 
            v-hasPermi="['lkshop:businessClass:add']"
          >添加子分类</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['lkshop:businessClass:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改店铺分类对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="businessClassRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属店铺ID" prop="businessId">
          <el-input v-model="form.businessId" placeholder="请输入所属店铺ID" />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父分类" prop="parentId" v-if="form.level && form.level !== 1">
          <el-select v-model="form.parentId" placeholder="请选择父分类" style="width: 100%">
            <el-option
              v-for="item in getParentOptionsByLevel(form.level, form.parentId)"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类等级" prop="level">
          <el-input v-model="form.level" placeholder="请输入分类等级" />
        </el-form-item>
        <el-form-item label="商品类型" prop="goodsType">
          <el-select v-model="form.goodsType" placeholder="请选择商品类型" style="width: 100%">
            <el-option label="实物商品" :value="1" />
            <el-option label="虚拟商品" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类图片" prop="img">
          <image-upload v-model="form.img"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BusinessClass">
import { listBusinessClass, treeListBusinessClass, getBusinessClass, delBusinessClass, addBusinessClass, updateBusinessClass } from "@/api/lkshop/businessClass"

const { proxy } = getCurrentInstance()

const businessClassList = ref([])
const parentOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    businessId: null,
    name: null,
    parentId: null,
    level: null,
    goodsType: null,
    img: null
  },
  rules: {
    businessId: [
      { required: true, message: "所属店铺ID不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "分类名称不能为空", trigger: "blur" }
    ],
    level: [
      { required: true, message: "分类等级不能为空", trigger: "blur" }
    ],
    goodsType: [
      { required: true, message: "商品类型不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询店铺分类层级列表 */
function getList() {
  loading.value = true
  treeListBusinessClass(queryParams.value).then(response => {
    businessClassList.value = response.data
    loading.value = false
  })
}

/** 获取父分类选项 */
function getParentOptions() {
  treeListBusinessClass({}).then(response => {
    // 获取所有分类数据，用于父分类选择
    parentOptions.value = response.data
  }).catch(error => {
    console.error('获取父分类选项失败:', error)
  })
}

/** 根据分类等级获取对应的父分类选项 */
function getParentOptionsByLevel(level, currentParentId = null) {
  if (!level) return []
  
  // 扁平化树形结构数据
  const flattenCategories = (categories) => {
    let result = []
    categories.forEach(category => {
      result.push(category)
      if (category.children && category.children.length > 0) {
        result = result.concat(flattenCategories(category.children))
      }
    })
    return result
  }
  
  const allCategories = flattenCategories(parentOptions.value)
  
  let filteredCategories = []
  if (level === 2) {
    // 二级分类的父分类是一级分类
    filteredCategories = allCategories.filter(item => {
      const itemLevel = parseInt(item.level)
      return itemLevel === 1
    })
  } else if (level === 3) {
    // 三级分类的父分类是二级分类
    if (currentParentId) {
      // 找到当前二级分类所属的一级分类
      const currentCategory = allCategories.find(item => item.id === currentParentId)
      if (currentCategory && currentCategory.parentId) {
        // 只显示同一级分类下的二级分类
        filteredCategories = allCategories.filter(item => {
          const itemLevel = parseInt(item.level)
          return itemLevel === 2 && item.parentId === currentCategory.parentId
        })
      } else {
        // 如果没有找到父分类，显示所有二级分类
        filteredCategories = allCategories.filter(item => {
          const itemLevel = parseInt(item.level)
          return itemLevel === 2
        })
      }
    } else {
      // 如果没有指定当前父分类，显示所有二级分类
      filteredCategories = allCategories.filter(item => {
        const itemLevel = parseInt(item.level)
        return itemLevel === 2
      })
    }
  }
  
  return filteredCategories
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    businessId: null,
    name: null,
    parentId: null,
    level: null,
    goodsType: null,
    img: null
  }
  proxy.resetForm("businessClassRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  // 如果搜索条件为空，显示所有分类
  if (!queryParams.value.name && !queryParams.value.businessId) {
    getList()
    return
  }
  
  // 如果有搜索条件，调用搜索接口
  loading.value = true
  treeListBusinessClass(queryParams.value).then(response => {
    businessClassList.value = response.data
    loading.value = false
    
    // 如果有搜索结果，显示提示
    if (response.data && response.data.length > 0) {
      const totalCount = countAllCategories(response.data)
      proxy.$modal.msgSuccess(`搜索完成，共找到 ${totalCount} 个分类`)
    } else {
      proxy.$modal.msgWarning('未找到匹配的分类')
    }
  }).catch(error => {
    console.error('搜索失败:', error)
    loading.value = false
    proxy.$modal.msgError('搜索失败，请重试')
  })
}

/** 统计所有分类数量（包括子分类） */
function countAllCategories(categories) {
  let count = 0
  const countRecursive = (cats) => {
    cats.forEach(cat => {
      count++
      if (cat.children && cat.children.length > 0) {
        countRecursive(cat.children)
      }
    })
  }
  countRecursive(categories)
  return count
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 刷新列表 */
function handleRefresh() {
  getList()
}

/** 新增一级分类 */
function handleAddFirstLevel() {
  reset()
  form.value.level = 1
  form.value.parentId = null
  open.value = true
  title.value = "添加一级分类"
}

/** 新增子分类 */
function handleAddSubCategory(row) {
  reset()
  // 修改：根据当前分类等级确定子分类等级
  const newLevel = row.level + 1
  form.value.level = newLevel
  form.value.parentId = row.id
  form.value.businessId = row.businessId
  
  // 确保父分类选项是最新的
  getParentOptions()
  
  open.value = true
  
  // 根据新等级设置标题
  let levelText = ''
  if (newLevel === 2) {
    levelText = '二级'
  } else if (newLevel === 3) {
    levelText = '三级'
  } else {
    levelText = `${newLevel}级`
  }
  title.value = `添加${levelText}分类`
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id
  getBusinessClass(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改分类"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["businessClassRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBusinessClass(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addBusinessClass(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _id = row.id
  proxy.$modal.confirm('是否确认删除分类"' + row.name + '"？').then(function() {
    return delBusinessClass(_id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

getList()
getParentOptions()
</script>
